// 仪表盘功能模块 - 纯静态版本
class DashboardManager {
    constructor() {
        this.init();
    }

    init() {
        // 加载统计数据
        this.loadStatistics();
        
        // 加载最近活动
        this.loadRecentActivity();
    }

    // 加载统计数据（纯静态版本）
    async loadStatistics() {
        try {
            console.log('📊 从本地 JSON 加载统计数据...');
            const blogsResponse = await fetch('../frontend/AiBlog/Blogs.json');
            
            if (blogsResponse.ok) {
                const data = await blogsResponse.json();
                const blogs = Array.isArray(data) ? data : (data.blogs || []);
                this.updateStatistics(blogs);
                console.log('✅ 统计数据加载成功');
            } else {
                console.error('❌ 加载失败:', blogsResponse.status);
                this.showErrorStats();
            }
        } catch (error) {
            console.error('❌ 加载统计数据失败:', error);
            this.showErrorStats();
        }
    }

    // 更新统计数据
    updateStatistics(blogs) {
        const totalBlogs = blogs.length;
        const publishedBlogs = blogs.filter(blog => blog.status === 'published').length;
        const draftBlogs = blogs.filter(blog => blog.status === 'draft').length;
        
        // 找到最近更新的博客
        let lastUpdate = '无';
        if (blogs.length > 0) {
            const sortedBlogs = blogs.sort((a, b) => 
                new Date(b.updatedAt || b.createdAt || b.publishDate) - 
                new Date(a.updatedAt || a.createdAt || a.publishDate)
            );
            if (sortedBlogs[0].updatedAt || sortedBlogs[0].createdAt || sortedBlogs[0].publishDate) {
                lastUpdate = commonManager.formatDate(
                    sortedBlogs[0].updatedAt || sortedBlogs[0].createdAt || sortedBlogs[0].publishDate
                );
            }
        }

        // 更新DOM
        this.updateElement('blogCount', totalBlogs);
        this.updateElement('publishedCount', publishedBlogs);
        this.updateElement('draftCount', draftBlogs);
        this.updateElement('lastUpdate', lastUpdate);
    }

    // 显示错误统计
    showErrorStats() {
        this.updateElement('blogCount', '加载失败');
        this.updateElement('publishedCount', '加载失败');
        this.updateElement('draftCount', '加载失败');
        this.updateElement('lastUpdate', '加载失败');
    }

    // 更新元素内容
    updateElement(id, value) {
        const element = document.getElementById(id);
        if (element) {
            element.textContent = value;
        }
    }

    // 加载最近活动
    async loadRecentActivity() {
        try {
            const blogsResponse = await fetch('../frontend/AiBlog/Blogs.json');
            if (blogsResponse.ok) {
                const data = await blogsResponse.json();
                const blogs = Array.isArray(data) ? data : (data.blogs || []);
                this.updateRecentActivity(blogs);
            } else {
                this.showNoActivity();
            }
        } catch (error) {
            console.error('Error loading recent activity:', error);
            this.showNoActivity();
        }
    }

    // 更新最近活动
    updateRecentActivity(blogs) {
        const activityContainer = document.getElementById('recentActivity');
        if (!activityContainer) return;

        if (blogs.length === 0) {
            this.showNoActivity();
            return;
        }

        // 按更新时间排序，取最近5条
        const recentBlogs = blogs
            .sort((a, b) => 
                new Date(b.updatedAt || b.createdAt || b.publishDate) - 
                new Date(a.updatedAt || a.createdAt || a.publishDate)
            )
            .slice(0, 5);

        const activityHTML = recentBlogs.map(blog => {
            const time = commonManager.formatDate(blog.updatedAt || blog.createdAt || blog.publishDate);
            const status = blog.status === 'published' ? '已发布' : '草稿';
            const statusColor = blog.status === 'published' ? 'text-green-600' : 'text-yellow-600';
            
            return `
                <div class="flex items-center text-sm text-gray-600">
                    <i class="fa-solid fa-circle text-blue-500 mr-3 text-xs"></i>
                    <span class="flex-1">${blog.title}</span>
                    <span class="text-xs ${statusColor} mr-2">${status}</span>
                    <span class="text-xs text-gray-400">${time}</span>
                </div>
            `;
        }).join('');

        activityContainer.innerHTML = activityHTML;
    }

    // 显示无活动状态
    showNoActivity() {
        const activityContainer = document.getElementById('recentActivity');
        if (activityContainer) {
            activityContainer.innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fa-solid fa-inbox text-4xl mb-3 opacity-50"></i>
                    <p>暂无活动记录</p>
                </div>
            `;
        }
    }
}

// 初始化仪表盘管理器
const dashboardManager = new DashboardManager();

// 导出供其他模块使用
window.DashboardManager = DashboardManager;
window.dashboardManager = dashboardManager;

console.log('🎉 纯静态仪表盘管理器已加载');
